package com.bzframework.core.response.advice;

import com.bzframework.core.response.BaseResponse;
import com.bzframework.core.response.ErrorCode;
import com.bzframework.core.response.ResultUtils;
import com.bzframework.core.response.exception.BusinessException;
import com.bzframework.core.response.exception.NoAuthorizationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常捕捉
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage());
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(NoAuthorizationException.class)
    public BaseResponse<?> noAuthorizationExceptionHandler(NoAuthorizationException e) {
        return ResultUtils.error(ErrorCode.NO_AUTHORIZATION);
    }

}
